<template>
  <div class="topic-detail">
    <h4 class="title">{{ topic.title }}</h4>
    <p class="author">发布者: {{ topic.author }}</p>
    <div class="content">{{ topic.content }}</div>
    <!-- 评论区域 -->
    <div class="comment-area">
      <el-input type="text" v-model="commentContent">
        <template #append>
          <el-button @click="publishComment">发布评论</el-button>
        </template>
      </el-input>
    </div>
    <div class="comment-list" v-if="topic.comments && topic.comments.length>0">
      <div v-for="(c,i) in topic.comments" :key="c.id">
        <p>第{{ i + 1 }}条评论: {{ c.author }}说</p>
        <div>{{ c.content }}</div>
      </div>
    </div>
    <router-link to="/topic/list">返回列表</router-link>
  </div>
</template>

<script>
export default {
  name: 'TopicDetail',
  data(){
    return {
      topic: '',
      commentContent:''
    }
  },
  methods: {
    publishComment(){
      let comment = {
        id: 0 ,
        author: '佚名',
        content: this.commentContent
      }

      this.commentContent = '';

      // 获得当前话题的所有评论
      const comments = this.topic.comments;
      if( comments ) {
        // 在 comments 数组中寻找 最大的 id
        let maxId = comments.reduce( (prev,curr) => Math.max( prev, curr.id ), 0 );
        comment.id = maxId + 1 ;
        comments.push( comment );
        return;
      }

      comment.id = Number( this.topic.id + '001' ) ;
      this.topic.comments = [ comment ];
    }
  },
  created(){

    let topicId = this.$route.params.id ;

    // 采用 fetch 抓取数据
    let p = fetch('/topics.json');
    p.then( resp => resp.json() )
     .then( topics => {
       let topic = topics.find( t => t.id == topicId );
       if( topic ) {
         this.topic = topic;
       }
     }).catch( reason => console.log( reason ) );
  }
}
</script>

<style>
.topic-detail {
  margin: 20px;
  width: 100%;
  background: #fff;
}
.topic-detail .title {
  margin: 20px;
  text-align: center;
}

.topic-detail .author {
  margin: 10px 20px;
  text-align: center;
}

.topic-detail .content {
  margin: auto 20px;
  border: 1px solid #8899ff;
}

.comment-area {
  margin: 20px;
}

.comment-list{
  margin: 20px;
  border: 1px solid #dfdfdf ;
}

.comment-list>div {
  margin: 5px ;
  border: 1px solid #080;
}
</style>